from typing import Any, List, Optional

from fastapi import APIRouter, Depends, HTTPException, Query, status, UploadFile, File
from sqlalchemy.ext.asyncio import AsyncSession

from app.api import deps
from app.models.user import User
from app.schemas.document import DocumentCreate, DocumentUpdate, DocumentResponse
from app.services import document as document_service


router = APIRouter()


@router.get("/", response_model=List[DocumentResponse])
async def read_documents(
    db: AsyncSession = Depends(deps.get_db),
    skip: int = 0,
    limit: int = 100,
    project_id: Optional[int] = None,
    document_type: Optional[str] = None,
    current_user: User = Depends(deps.get_current_active_user),
) -> Any:
    """获取文档列表，可按项目和文档类型筛选"""
    documents = await document_service.get_documents(
        db=db, skip=skip, limit=limit,
        project_id=project_id, document_type=document_type
    )
    return documents


@router.post("/", response_model=DocumentResponse, status_code=status.HTTP_201_CREATED)
async def create_document(
    *,
    db: AsyncSession = Depends(deps.get_db),
    document_in: DocumentCreate,
    current_user: User = Depends(deps.get_current_active_user),
) -> Any:
    """创建文档记录"""
    document = await document_service.create_document(
        db=db, obj_in=document_in, creator_id=current_user.id
    )
    return document


@router.post("/upload")
async def upload_document(
    *,
    file: UploadFile = File(...),
    project_id: int,
    document_type: str,
    title: str,
    description: Optional[str] = None,
    task_id: Optional[int] = None,
    parent_id: Optional[int] = None,
    db: AsyncSession = Depends(deps.get_db),
    current_user: User = Depends(deps.get_current_active_user),
) -> Any:
    """上传文档文件并创建文档记录"""
    # 这里应该实现文件上传逻辑，保存文件并获取文件路径、大小等信息
    # 为简化示例，这里仅返回文件信息，实际实现需要处理文件存储
    file_path = f"uploads/{project_id}/{file.filename}"  # 示例路径
    file_size = 0  # 示例大小，实际应计算文件大小
    mime_type = file.content_type
    
    # 创建文档记录
    document_in = DocumentCreate(
        title=title,
        description=description,
        document_type=document_type,
        file_path=file_path,
        file_size=file_size,
        mime_type=mime_type,
        version="1.0",  # 初始版本
        is_latest=True,
        project_id=project_id,
        task_id=task_id,
        parent_id=parent_id,
    )
    
    document = await document_service.create_document(
        db=db, obj_in=document_in, creator_id=current_user.id
    )
    
    return {
        "id": document.id,
        "title": document.title,
        "file_name": file.filename,
        "content_type": file.content_type,
        "file_path": file_path,
    }


@router.get("/{document_id}", response_model=DocumentResponse)
async def read_document(
    *,
    db: AsyncSession = Depends(deps.get_db),
    document_id: int,
    current_user: User = Depends(deps.get_current_active_user),
) -> Any:
    """获取特定文档详情"""
    document = await document_service.get_document_by_id(db=db, id=document_id)
    if not document:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Document not found",
        )
    return document


@router.put("/{document_id}", response_model=DocumentResponse)
async def update_document(
    *,
    db: AsyncSession = Depends(deps.get_db),
    document_id: int,
    document_in: DocumentUpdate,
    current_user: User = Depends(deps.get_current_active_user),
) -> Any:
    """更新文档"""
    document = await document_service.get_document_by_id(db=db, id=document_id)
    if not document:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Document not found",
        )
    # 检查权限：只有文档创建者或超级用户可以更新文档
    if document.creator_id != current_user.id and not current_user.is_superuser:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Not enough permissions",
        )
    document = await document_service.update_document(db=db, db_obj=document, obj_in=document_in)
    return document


@router.delete("/{document_id}", response_model=DocumentResponse)
async def delete_document(
    *,
    db: AsyncSession = Depends(deps.get_db),
    document_id: int,
    current_user: User = Depends(deps.get_current_active_user),
) -> Any:
    """删除文档"""
    document = await document_service.get_document_by_id(db=db, id=document_id)
    if not document:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Document not found",
        )
    # 检查权限：只有文档创建者或超级用户可以删除文档
    if document.creator_id != current_user.id and not current_user.is_superuser:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Not enough permissions",
        )
    document = await document_service.delete_document(db=db, id=document_id)
    return document